<template>
  <div style="border: 1px solid #E8E8E8;border-radius: 5px;padding: 15px">
    <a-button type="primary" v-has="'customer:addCostProduction'" v-show="this.customerInfo.isTransferForm === 1" style="margin-bottom: 10px" @click="addCostProduction()">选择成本制作</a-button>
    <!--<a-button type="primary" v-has="'customer:printTable'" style="margin-bottom: 10px;margin-left: 10px;margin-right: 10px" @click="printTable">
      下载pdf
    </a-button>-->
    <a-button type="primary" v-has="'customer:saveScheme'" v-if="this.customerInfo.isTransferForm === 1" style="margin-left: 10px;margin-bottom: 10px;margin-right: 10px" @click="saveScheme(1)">保存方案</a-button>
    <a-button type="primary" v-has="'customer:clearScheme'" v-if="this.customerInfo.isTransferForm === 1" style="margin-bottom: 10px;margin-right: 10px" @click="clearAllScheme()">清除所有方案</a-button>
    <a-button type="primary" v-has="'customer:copyScheme'" v-if="this.materialCost.length !== 0" style="margin-bottom: 10px;margin-right: 10px" @click="copyScheme()">方案复制</a-button>
    <a-button type="primary" v-if="this.customerInfo.isTransferForm === 1 && this.transferFormFlag == true" v-has="'customer:transferForm'" style="margin-bottom: 10px" @click="transferForm()">转单</a-button>
    <a-button disabled v-if="this.customerInfo.isTransferForm === 2 || this.transferFormFlag == false" style="margin-bottom: 10px">已转单</a-button>
    <!--<a-button type="primary" v-if="this.customerInfo.isTransferForm === 2" v-has="'customer:placeOrder'" style="margin-bottom: 10px;margin-left: 10px" @click="placeOrder()">下单</a-button>-->
    <a-row :gutter="10">
      <div style="background: lightgrey;">
        <!-- <a-col :span="12" style="margin-bottom: 20px;height: calc(100vh - 357px);overflow: auto" v-if="this.materialCost.length != 0">
          <a-card v-for="(item,materialIndex) in materialCost" :key="materialIndex" :bordered="false" style="width: 100%;">
            <template #title>
              <span>{{item.costTypeName}}</span>
              <span style="color: red;margin-left: 5px">( 小计：￥{{calculateMaterialPrice(item.materialList)}} )</span>
            </template>
            <a slot="extra" @click="clearScheme(item.chooseMaterialType,'material')">清除方案</a>

            <a-table
              :id="'material'+item.chooseMaterialType"
              ref="table"
              size="middle"
              :scroll="{x:true}"
              bordered
              :columns="materialColumns"
              :dataSource="item.materialList"
              :pagination="false"
              :loading="loading"
              @change="handleTableChange">

              <template slot="quantity" slot-scope="text, record, index">
                <a-input
                  type="number"
                  style="margin: -5px 0;border: none;background: white;width: 90px;text-align: center"
                  :value="text"
                  :id="'quantity'+record.key"
                  @blur="changeMaterialSubtotal(record.key)"
                  @change="(e) => handleChangeIndex1(e.target.value, record.key, 'quantity')"
                />
              </template>

              <template slot="unitPrice" slot-scope="text, record, index">
                <a-input
                  type="number"
                  style="margin: -5px 0;border: none;background: white;width: 120px;text-align: center"
                  :value="text"
                  :id="'unitPrice'+record.key"
                  @change="(e) => handleChangeIndex1(e.target.value, record.key, 'unitPrice')"
                  @blur="changeMaterialSubtotal(record.key,'unitPrice')"
                />
              </template>
              <template slot="costTypeSubtotal" slot-scope="text, record, index">
                <span :id="'costTypeSubtotal'+record.key">
                  {{text}}
                </span>
              </template>
              <template slot="operation" slot-scope="text, record, index">
                <div class="editable-row-operations">
                  <a-popconfirm title="确定删除这条记录吗" @confirm="() => onDelete(record,'material', materialIndex,index)">
                    <a>删除</a>
                  </a-popconfirm>
                </div>
              </template>
            </a-table>
          </a-card>
        </a-col> -->

        <a-col :span="24" style="height: calc(100vh - 280px);overflow: auto">
        <van-collapse v-model="activeName" accordion>
          <van-collapse-item
            :name="i"
            v-for="(item,i) in allList"
            :key="i">
            <template #title>
              <div style="display:flex;justify-content:space-between;font-size:13px;">
                <div>
                  <span>{{ item.costTypeName }}</span>
                  <span style="color:red;">（小计：￥{{ item.costTypeSubtotal }}）</span>
                </div>
                <a v-if="item.chooseMaterialType" @click.stop="clearScheme(item.chooseMaterialType,'material')">清除方案</a>
                <a v-if="item.chooseKindOfWork" @click.stop="clearScheme(item.chooseKindOfWork,'price')">清除方案</a>
              </div>
            </template>
            <van-collapse v-model="item.openList">
              <van-collapse-item
                :name="index+100"
                v-for="(obj,index) in item.priceList"
                :key="index+100">
                <template #title>
                  <div style="font-size:12px;">
                    <span>{{ obj.materialName || obj.constructionPlace }}</span>
                    <span style="color:red;">（小计：￥{{ obj.costTypeSubtotal }}）</span>
                  </div>
                </template>
                <div class="list">
                  <div v-if="obj.materialName">材料名称：{{ obj.materialName }}</div>
                  <div v-if="obj.kindOfWorkTypeName">工种类型：{{ obj.kindOfWorkTypeName }}</div>
                  <div v-if="obj.modelNumber">型号：{{ obj.modelNumber }}</div>
                  <div v-if="obj.specifications">规格：{{ obj.specifications }}</div>
                  <div v-if="obj.constructionPlace">施工部位：{{ obj.constructionPlace }}</div>
                  <div>单位：{{obj.unit}}</div>
                  <div>数量：
                    <a-input
                      type="number"
                      style="margin: -5px 0;border: none;background: white;width: 90px;text-align: center"
                      v-model="obj.quantity"
                      @blur="countPrice(i, index)"/>
                  </div>
                  <div>单价：
                    <a-input
                      type="number"
                      style="margin: -5px 0;border: none;background: white;width: 90px;text-align: center"
                      v-model="obj.unitPrice"
                      @blur="countPrice(i, index)"/>
                  </div>
                  <div>小计：<span style="margin-left: 2em;">{{obj.costTypeSubtotal}}</span></div>
                  <div>操作：
                    <a-popconfirm v-if="obj.materialName" title="确定删除这条记录吗" @confirm="() => onDelete(obj, 'material', i, index)">
                      <a>删除</a>
                    </a-popconfirm>
                    <a-popconfirm v-else title="确定删除这条记录吗" @confirm="() => onDelete(obj, 'price', i, index)">
                      <a>删除</a>
                    </a-popconfirm>
                  </div>
                </div>
              </van-collapse-item>
            </van-collapse>



          </van-collapse-item>
        </van-collapse>
        </a-col>
        <!-- <a-col :span="12" style="margin-bottom: 20px;height: calc(100vh - 357px);overflow: auto">
          <a-card v-for="(item,priceIndex) in priceManagementCost" :key="priceIndex" :bordered="false" style="width: 100%;">
            <template #title>
              <span>{{item.costTypeName}}</span>
              <span style="color: red;margin-left: 5px">( 小计：￥{{calculateArtificialPrice(item.priceList)}} )</span>
            </template>
            <a slot="extra" @click="clearScheme(item.chooseKindOfWork,'price')">清除方案</a>
            <a-table
              ref="table"
              :id="'price'+item.chooseKindOfWork"
              size="middle"
              :scroll="{x:true}"
              bordered
              :columns="priceColumns"
              :dataSource="item.priceList"
              :pagination="false"
              :loading="loading"
              @change="handleTableChange">

              <template slot="quantity" slot-scope="text, record, index">
                <a-input
                  type="number"
                  style="margin: -5px 0;border: none;background: white;width: 90px;text-align: center"
                  :value="text"
                  :id="'priceQuantity'+record.key"
                  @blur="changeMaterialSubtotal2(record.key)"
                  @change="(e) => handleChangeIndex2(e.target.value, record.key, 'quantity')"
                />
              </template>
              <template slot="unitPrice" slot-scope="text, record, index">
                <a-input
                  type="number"
                  style="margin: -5px 0;border: none;background: white;width: 120px;text-align: center"
                  :value="text"
                  :id="'priceUnitPrice'+record.key"
                  @change="(e) => handleChangeIndex2(e.target.value, record.key, 'unitPrice')"
                  @blur="changeMaterialSubtotal2(record.key)"
                />
              </template>
              <template slot="costTypeSubtotal" slot-scope="text, record, index">
                <span :id="'priceCostTypeSubtotal'+record.key">
                  {{text}}
                </span>
              </template>
              <template slot="operation" slot-scope="text, record, index">
                <div class="editable-row-operations">
                  <a-popconfirm title="确定删除这条记录吗" @confirm="() => onDelete(record,'price',priceIndex,index)">
                    <a>删除</a>
                  </a-popconfirm>
                </div>
              </template>
            </a-table>
          </a-card>
        </a-col> -->
      </div>
    </a-row>
    <a-row>
      <a-col :span="12">
        <div style="background: white;padding: 10px;padding-left: 20px;font-weight: bold;font-size: 16px;">
          订单总价：<span style="color: orangered">￥{{allPrice}}</span>
        </div>
      </a-col>
    </a-row>
    <add-cost-production-modal ref="addCostProductionModal" @ok="modalFormOk"></add-cost-production-modal>
    <select-customer-modal ref="selectCustomerModal"></select-customer-modal>
  </div>
</template>

<script>
  import printJS from 'print-js'
  import { deleteAction,postAction, putAction, getAction } from '@/api/manage'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { filterDictTextByCache } from '@comp/dict/JDictSelectUtil'
  import addCostProductionModal from './modules/addCostProductionModal'
  import selectCustomerModal from './modules/selectCustomerModal'
  export default {
    name: 'costProduction.vue',
    mixins: [JeecgListMixin, mixinDevice],
    components: {
      addCostProductionModal,selectCustomerModal,
    },
    props: {
      customerId: {
        required: true,
        default: 0
      },
    },
    data() {
      return {
        allList: [],
        allPrice: 0,
        activeName: '',
        htmlTitle: '成本制作', //这是定义导出的名字，不写这个默认下载的名字是undefinded
        totalPrice: 0,
        materialColumns: [
          {
            title: '材料名称',
            dataIndex: 'materialName',
            align: 'center',
          },
          {
            title: '型号',
            dataIndex: 'modelNumber',
            align: 'center',
          },
          {
            title: '规格',
            dataIndex: 'specifications',
            align: 'center',
          },
          {
            title: '单位',
            dataIndex: 'unit',
            align: 'center',
          },
          {
            title: '数量',
            dataIndex: 'quantity',
            align: 'center',
            width: 100,
            scopedSlots: { customRender: 'quantity' },
          },
          {
            title: '单价',
            dataIndex: 'unitPrice',
            align: 'center',
            width: 120,
            scopedSlots: { customRender: 'unitPrice' },
          },
          {
            title: '小计',
            width: 120,
            dataIndex: 'costTypeSubtotal',
            scopedSlots: { customRender: 'costTypeSubtotal' },
            align: 'center',
          },
          {
            title: '操作',
            dataIndex: 'operation',
            align: 'center',
            fixed: 'right',
            width: 90,
            scopedSlots: { customRender: 'operation' }
          }
        ],
        priceColumns: [
          {
            title: '工种类型',
            dataIndex: 'kindOfWorkTypeName',
            align: 'center',
          },
          {
            title: '施工部位',
            dataIndex: 'constructionPlace',
            align: 'center',
          },
          {
            title: '单位',
            dataIndex: 'unit',
            align: 'center',
          },
          {
            title: '数量',
            dataIndex: 'quantity',
            align: 'center',
            scopedSlots: { customRender: 'quantity' },
          },
          {
            title: '单价',
            dataIndex: 'unitPrice',
            align: 'center',
            scopedSlots: { customRender: 'unitPrice' },
          },
          {
            title: '小计',
            dataIndex: 'costTypeSubtotal',
            align: 'center',
            scopedSlots: { customRender: 'costTypeSubtotal' },
          },
          {
            title: '操作',
            dataIndex: 'operation',
            align: 'center',
            fixed: 'right',
            width: 90,
            scopedSlots: { customRender: 'operation' }
          }
        ],
        dataSource: [],
        materialCost: [],
        priceManagementCost: [],
        tempData: [],
        keyIndex1: 0,
        keyIndex2: 0,
        editingKey: '',
        url: {
          list: '/ghCustomerChooseCost/list',
          delete: '/ghCustomerChooseCost/delete',
          edit: "/ghCustomerChooseCost/edit",
          transferFormUrl: "/ghProjectTransferForm/add",
          getCustomerInfoById: '/ghCustomerInfo/getCustomerInfoById',
          clearSchemeUrl: "/ghCustomerChooseCost/clearScheme",
          clearAllSchemeUrl: "/ghCustomerChooseCost/clearAllScheme",
        },
        materialData: [],
        priceManagementData: [],
        cacheData: [],
        cacheData2: [],
        customerInfo:{},
        transferFormFlag: true,
        loading: false,
        selectedRowKeys1: [],
        selectedRows1: [],
        selectedRowKeys2: [],
        selectedRows2: [],
      }
    },
    created() {
      this.getCustomerInfo()
      let _this = this;
      this.calculateTotalPrice();
      window.totalPrice = _this.totalPrice
      window.clearNoNum = _this.clearNoNum
      window.handleInput = _this.handleInput



    },
    mounted(){
      //计算总价
      setTimeout(()=>{
        for(let i=0;i<this.allList.length;i++){
          this.countPrice(i,0)
        }
      },1000)
    },
    methods: {
      //计算每一个方案
      countPrice(i, index){
        let obj = this.allList[i].priceList[index]
        let list = this.allList[i].priceList
        let num = 0

        this.$set(this.allList[i].priceList[index], 'costTypeSubtotal', obj.quantity*obj.unitPrice)
        for(let n=0;n<list.length;n++){
          num = num + list[n].costTypeSubtotal
        }
        this.allList[i].costTypeSubtotal = num
        setTimeout(()=>{
          this.countPriceAll()
        },500)

      },
      //计算总价
      countPriceAll(){
        let price = 0
        for(let i=0;i<this.allList.length;i++){
          price = price + (this.allList[i].costTypeSubtotal*1)
        }
        this.$set(this, 'allPrice', price)
      },
      //每种材料类型小计汇总
      calculateMaterialPrice(materialArrData){
        let materialSubtotal = 0;
        materialArrData.forEach(function (item) {
           let subtotal = item.unitPrice * item.quantity;
           materialSubtotal += subtotal;
        })
        return materialSubtotal.toFixed(2);
      },
      //每种人工类型小计汇总
      calculateArtificialPrice(artificialArrData){
        let artificialSubtotal = 0;
        artificialArrData.forEach(function (item) {
          let subtotal = item.unitPrice * item.quantity;
          artificialSubtotal += subtotal;
        })
        return artificialSubtotal.toFixed(2);
      },
      //转单
      transferForm(){
        if (this.materialData.length === 0){
          this.$message.warning("请制作材料成本方案，再进行转单！")
          return;
        }
        let that = this;
        let params = {
          customerId : this.customerId,
        };
        this.$confirm({
          title: "确认提醒",
          content: "是否确定转单操作?",
          onOk: function () {
            that.loading = true;
            postAction(that.url.transferFormUrl, params).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.transferFormFlag = false;
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.loading = false;
            })
          }
        });
      },
      clearNoNum(obj) {
        obj.value = obj.value.replace(/[^\d.]/g, '')  //清除“数字”和“.”以外的字符
        obj.value = obj.value.replace(/\.{2,}/g, '.') //只保留第一个. 清除多余的
        obj.value = obj.value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
        obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')//只能输入两个小数
        if (obj.value.indexOf('.') < 0 && obj.value != '') {//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
          obj.value = parseFloat(obj.value)
        }
      },
      //保存方案
      saveScheme(messageFlag){
        let allCostData = this.materialData.concat(this.priceManagementData);
        putAction(this.url.edit, {
          customerId: this.customerId,
          costProductions: allCostData
        }).then(res => {
          if (res.success) {
            if (messageFlag){
              this.$message.success(res.message)
            }
            this.loadData()
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      //清除方案
      clearScheme(typeValue,type){
        if (this.customerInfo.isTransferForm === 2){
          this.$message.warning("当前客户方案已转单，无法清除")
          return;
        }
        let that = this;
        this.$confirm({
          title: "确认删除",
          content: "是否确定删除当前表格材料数据?",
          onOk: function () {
            let costType = 0;
            if (type === 'material'){
              costType = 1;
            }else if (type === 'price'){
              costType = 2;
            }
            deleteAction(that.url.clearSchemeUrl, { customerId: that.customerId,costType:costType,costTypeValue:typeValue}).then((res) => {
              if (res.success) {
                that.saveScheme();
                that.$message.success(res.message);
              } else {
                that.$message.warning(res.message);
              }
            })
          }
        });
      },
      //清除所有方案
      clearAllScheme(){
        let that = this;
        this.$confirm({
          title: "确认删除",
          content: "是否确定删除当前客户所有成本制作数据?",
          onOk: function () {
            that.saveScheme();
            deleteAction(that.url.clearAllSchemeUrl, { customerId: that.customerId}).then((res) => {
              if (res.success) {
                that.saveScheme();
                that.$message.success(res.message);
              } else {
                that.$message.warning(res.message);
              }
            })
          }
        });
      },
      //方案复制
      copyScheme(){
        this.$refs.selectCustomerModal.add(this.customerId);
        this.$refs.selectCustomerModal.title = "选择客户";
      },
      //表格确定回调
      handleChangeIndex1(value, key, column) {
        const dataSource = [...this.materialData]
        const target = dataSource[key]
        if (target) {
          target[column] = Math.abs(value)
          this.materialData = dataSource
        }
      },
      handleChangeIndex2(value, key, column) {
        const dataSource = [...this.priceManagementData]
        const target = dataSource[key]
        if (target) {
          target[column] = Math.abs(value)
          this.priceManagementData = dataSource
        }
      },
      //计算小计
      changeMaterialSubtotal(key,column) {
        let quantity = document.getElementById('quantity' + key)
        let unitPrice = document.getElementById('unitPrice' + key)
        let costTypeSubtotal = document.getElementById('costTypeSubtotal' + key)
        let subtotal = parseFloat(quantity.value * Math.abs(unitPrice.value)).toFixed(2)
        costTypeSubtotal.innerText = subtotal
        const target = this.materialData.find(item => key === item.key)
        if (target) {
          target['costTypeSubtotal'] = subtotal
        }
        this.calculateTotalPrice()
      }
      ,
      changeMaterialSubtotal2(key) {
        let quantity = document.getElementById('priceQuantity' + key)
        let unitPrice = document.getElementById('priceUnitPrice' + key)
        let costTypeSubtotal = document.getElementById('priceCostTypeSubtotal' + key)

        let subtotal = parseFloat(quantity.value * Math.abs(unitPrice.value)).toFixed(2)
        costTypeSubtotal.innerText = subtotal
        const target = this.priceManagementData.find(item => key === item.key)
        if (target) {
          target['costTypeSubtotal'] = subtotal
        }
        this.calculateTotalPrice()
      },
      //计算总价
      calculateTotalPrice() {
        this.totalPrice = 0
        let result = 0
        for (let i = 0; i < this.materialData.length; i++) {
          //result += parseFloat(this.materialData[i].costTypeSubtotal)
          this.totalPrice += parseFloat(this.materialData[i].costTypeSubtotal)
        }
        for (let i = 0; i < this.priceManagementData.length; i++) {

          //result += parseFloat(this.priceManagementData[i].costTypeSubtotal)
          this.totalPrice += parseFloat(this.priceManagementData[i].costTypeSubtotal)
        }
      },
      onDelete(record,type,index,rowIndex) {
        if (this.customerInfo.isTransferForm === 2){
          this.$message.warning("当前客户方案已转单，无法删除")
          return;
        }
        let materialDataIndex = 0;
        let priceDataIndex = 0;
        if (type === "material"){
          let deleteKeyIndex = 0;
          this.materialCost[index].materialList.splice(rowIndex,1)
          this.materialCost[index].materialList.forEach(function (item) {
            item['key'] = deleteKeyIndex;
            let subtotal = document.getElementById('costTypeSubtotal' + item.key)
            if (item.costTypeSubtotal != null){
              subtotal.innerText = item.costTypeSubtotal;
            }else {
              subtotal.innerText = ""
            }
            deleteKeyIndex++;
          })
          this.materialData.map((item,index)=>{
            if (item.id === record.id){
              this.materialData.splice(item.key,1);
            }
          })
          this.materialData.forEach(function (item) {
            item.key = materialDataIndex;
            materialDataIndex++;
          })
        }else if (type === "price") {
          let deleteKeyIndex = 0;
          this.priceManagementCost[index].priceList.splice(rowIndex,1)
          this.priceManagementCost[index].priceList.forEach(function (item) {
            item['key'] = deleteKeyIndex;
            let subtotal = document.getElementById('priceCostTypeSubtotal' + item.key)
            if (item.costTypeSubtotal != null){
              subtotal.innerText = item.costTypeSubtotal;
            }else {
              subtotal.innerText = ""
            }
            deleteKeyIndex++;
          })
          this.priceManagementData.map((item,index)=>{
            if (item.id === record.id){
              this.priceManagementData.splice(item.key,1);
            }
          })
          this.priceManagementData.forEach(function (item) {
            item.key = priceDataIndex;
            priceDataIndex++;
          })
        }
        this.totalPrice -= record.costTypeSubtotal
        if (record.id) {
          deleteAction(this.url.delete, { id: record.id }).then(res => {
            if (res.success) {
              this.$message.success(res.message)
            } else {
              this.$message.warning(res.message)
            }
          })
        }
      },
      formatPrice(price) {
        return price.toFixed(2)
      },
      printTable() {
        //需要打印的数据
        const needPrintData = []
        for (let i = 0; i < this.dataSource.length; i++) {
          for (let j = 0; j < this.dataSource[i].children.length; j++) {
            let obj = this.dataSource[i].children[j]
            needPrintData.push({
              costName: obj.costName,
              costNum: obj.costNum,
              costUnit: obj.costUnit,
              costPrice: obj.costPrice,
              costSubtotal: obj.costSubtotal,
              projectDescription: obj.projectDescription
            })
          }
        }
        for (let i = 0;i<this.materialData.length;i++){
          let unit = this.materialData[i].specifications;
          if (unit == null || unit === ""){
            unit = "无"
          }
          needPrintData.push({
            materialName: this.materialData[i].materialName,
            constructionPlace: "无",
            unit: unit,
            quantity: this.materialData[i].quantity,
            unitPrice: this.materialData[i].unitPrice,
            costTypeSubtotal: this.materialData[i].costTypeSubtotal,
          })
        }
        for (let i = 0;i<this.priceManagementData.length;i++){
          needPrintData.push({
            materialName: this.priceManagementData[i].kindOfWorkTypeName,
            constructionPlace: this.priceManagementData[i].constructionPlace,
            unit: this.priceManagementData[i].unit,
            quantity: this.priceManagementData[i].quantity,
            unitPrice: this.priceManagementData[i].unitPrice,
            costTypeSubtotal: this.priceManagementData[i].costTypeSubtotal,
          })
        }
        needPrintData.push({
          materialName: '<span style="color: orangered">总计</span>',
          constructionPlace: '<span style="color: orangered;">' + '￥' + this.formatPrice(this.totalPrice) + '</span>',
          unit: '',
          quantity: '',
          unitPrice: '',
          costTypeSubtotal: ''
        })

        printJS({
          printable: needPrintData,
          properties: [
            {
              field: 'materialName',
              displayName: '名称/人工种类',
              columnSize: '20%'
            },
            {
              field: 'constructionPlace',
              displayName: '施工部位',
              columnSize: '20%',
            },
            {
              field: 'unit',
              displayName: '单位/规格',
              columnSize: '7%'
            },
            {
              field: 'quantity',
              displayName: '数量',
              columnSize: '8%'
            },
            {
              field: 'unitPrice',
              displayName: '单价',
              columnSize: '8%'
            },
            {
              field: 'costTypeSubtotal',
              displayName: '小计',
              columnSize: '8%'
            },

          ],
          type: 'json',
          header: '成本制作',
          headerStyle: 'text-align:center;',
          gridHeaderStyle: 'font-weight:bold;font-size:13px;border:1px solid #ccc;',
          gridStyle: 'font-weight:normal;border:1px solid #ccc;margin-bottom: -1px;font-size:10px',
        })
      },

      getCostProductionValue(text) {
        return filterDictTextByCache('cost_production_cost_type', text) + '成本'
      },
      addCostProduction() {
        this.saveScheme()
        this.$refs.addCostProductionModal.show(this.customerId);
      },
      modalFormOk() {
        this.loadData();
      },
      loadData(arg) {
        if (!this.url.list) {
          this.$message.error('请设置url.list属性!')
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1
        }
        let params = {}
        params.customerId = this.customerId;
        this.loading = true
        this.tempData = []
        //this.editingKey = "";
        this.keyIndex1 = 0
        this.keyIndex2 = 0
        this.materialData = [];
        this.priceManagementData =[];
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            this.materialCost = res.result.materialCost
            this.priceManagementCost = res.result.priceManagementCost
            this.totalPrice = 0
            for (let i = 0; i < this.materialCost.length; i++) {
              for (let j = 0; j < this.materialCost[i].materialList.length; j++) {
                this.totalPrice += this.materialCost[i].materialList[j].costTypeSubtotal
                this.materialCost[i].materialList[j].key = this.keyIndex1
                this.materialData.push(this.materialCost[i].materialList[j])
                this.keyIndex1++
              }
            }

            for (let i = 0; i < this.priceManagementCost.length; i++) {
              for (let j = 0; j < this.priceManagementCost[i].priceList.length; j++) {
                this.totalPrice += this.priceManagementCost[i].priceList[j].costTypeSubtotal
                this.priceManagementCost[i].priceList[j].key = this.keyIndex2
                this.priceManagementData.push(this.priceManagementCost[i].priceList[j])
                this.keyIndex2++
              }
            }
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }

            for(let i = 0; i < res.result.materialCost.length; i++){
              res.result.materialCost[i].priceList = res.result.materialCost[i].materialList
            }
            this.allList = [...res.result.materialCost, ...res.result.priceManagementCost]
            // for(let i = 0; i < this.allList.length; i++){
            //   for(let n = 0; n < this.allList[i].priceList.length; n++){
            //     this.allList[i].priceList[n].openList = ''
            //   }
            // }
            for(let i = 0; i < this.allList.length; i++){
              this.$set(this.allList[i], 'openList', [])
            }
            console.log(this.allList)
            this.loading = false
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.loading = false
        })
      },
      getCustomerInfo() {
        this.loading = true;
        getAction(this.url.getCustomerInfoById, {
          id: this.customerId
        }).then((res) => {
          if (res.success) {
            this.loading = false;
            this.customerInfo = res.result;
          }
        })
      },
      //深克隆对象的属性值
      deepClone1(obj) {
        let newObj = Array.isArray(obj) ? [] : {}
        if (obj && typeof obj === 'object') {
          for (let key in obj) {
            if (obj.hasOwnProperty(key)) {
              newObj[key] = (obj && typeof obj[key] === 'object') ? this.deepClone1(obj[key]) : obj[key]
            }
          }
        }
        return newObj
      },
      onSelectAll1(selected, selectedRows, changeRows) {
        if(selected) {
          let rows = [...selectedRows]
          this.selectedRows1 = this.selectedRows1.concat(rows)
        } else {
          changeRows.forEach(item => {
            const delIndex = this.selectedRows1.findIndex((val) => {
              return val.id === item.id
            })
            this.selectedRows1.splice(delIndex, 1)
          })
        }
      },
      onSelect1(record, selected) {
        if(selected) {
          this.selectedRows1.push(record);
        } else {
          const delIndex = this.selectedRows1.findIndex((val) => {
            return val.id === record.id
          })
          this.selectedRows1.splice(delIndex,1)
        }
      },
      onSelectChange1(selectedRowKeys) {
        this.selectedRowKeys1 = selectedRowKeys;
      },
      onSelectAll2(selected, selectedRows, changeRows) {
        if(selected) {
          let rows = [...selectedRows]
          this.selectedRows2 = this.selectedRows2.concat(rows)
        } else {
          changeRows.forEach(item => {
            const delIndex = this.selectedRows2.findIndex((val) => {
              return val.id === item.id
            })
            this.selectedRows2.splice(delIndex, 1)
          })
        }
      },
      onSelect2(record, selected) {
        if(selected) {
          this.selectedRows2.push(record);
        } else {
          const delIndex = this.selectedRows2.findIndex((val) => {
            return val.id === record.id
          })
          this.selectedRows2.splice(delIndex,1)
        }
      },
      onSelectChange2(selectedRowKeys) {
        this.selectedRowKeys2 = selectedRowKeys;
      },
    },
  }
</script>

<style scoped>
.list{
  line-height: 40px;
  border-top: 1px solid #f6f6f6;
  font-size: 13px;
}


  .editable-row-operations a {
    margin-right: 8px;
  }

  .ant-table-row-expand-icon {
    display: none !important;
  }

  .ant-table-row-expand-icon .ant-table-row-collapsed {
    display: none !important;
  }
</style>